package com.xxb.service.user.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxb.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2023/7/25 10:14
 * @description 微信工具类
 */
@Slf4j
public class WeixinLoginUtil {
    private static String appId = "wx2130f87b8f96cff7";
    private static  String appSecret = "35b85e279a908b191217d7a986f473a5";

    public static String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        HttpResponse response = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(params)).execute();
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new ServiceException("临时登陆凭证错误");
        }

        return openId;
    }
}
